package com.jxt.myjxtmanager.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.opengl.GLES10;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.jxt.myjxtmanager.BaseActivity;
import com.jxt.myjxtmanager.R;
import com.jxt.myjxtmanager.utils.Config;
import com.jxt.myjxtmanager.utils.choosePicture.PhotoUtilChange;
import com.jxt.myjxtmanager.utils.choosePicture.TakePicUtils;
import com.jxt.myjxtmanager.views.CustomProgressDialog;
import com.jxt.myjxtmanager.views.updateAvatar.ClipImageLayout;
import com.jxt.myjxtmanager.views.updateAvatar.ImageTool;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 头像剪切界面
 *
 * @author Administrator
 */
public class ClipImageActivity extends BaseActivity {

    private ClipImageLayout mClipImageLayout;
    private Bitmap bm;
    private String picturePath;

    @Override
    protected int getLayoutId() {
        // TODO Auto-generated method stub
        return R.layout.activity_clip_image;
    }

    @Override
    protected void initView() {

        Uri data = this.getIntent().getData();
        setToolbarTitle("我的资料");
        setToolbarNavigationIcon(R.drawable.ic_left_return);
        String[] filePathColumns = {MediaStore.Images.Media.DATA};
        if (data == null || filePathColumns == null) {
            Toast.makeText(getApplicationContext(), "图片加载失败", Toast.LENGTH_SHORT).show();
            return;
        }
//		Cursor c = this.getContentResolver().query(data, filePathColumns, null, null, null);
//		c.moveToFirst();
//		picturePath = c.getString(c.getColumnIndex(filePathColumns[0]));
//		c.close();
        picturePath = TakePicUtils.onPhotoFromPick(this, getIntent(), data);
        mClipImageLayout = (ClipImageLayout) findViewById(R.id.id_clipImageLayout);

        BitmapFactory.Options options = new BitmapFactory.Options();
        try {
            options.inSampleSize = calculateBitmapSampleSize(data) * 2;
            bm = BitmapFactory.decodeFile(picturePath, options);
            bm = ImageTool.changeDirectionBitmap(bm, picturePath, false);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        mClipImageLayout.mZoomImageView.setImageBitmap(bm);


    }


    private int calculateBitmapSampleSize(Uri bitmapUri) throws IOException {
        InputStream is = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        try {
            is = getContentResolver().openInputStream(bitmapUri);
            BitmapFactory.decodeStream(is, null, options); // Just get image size
        } finally {
            closeSilently(is);
        }

        int maxSize = getMaxImageSize();
        int sampleSize = 1;
        while (options.outHeight / sampleSize > maxSize || options.outWidth / sampleSize > maxSize) {
            sampleSize = sampleSize << 1;
        }
        return sampleSize;
    }


    private static final int SIZE_DEFAULT = 2048;
    private static final int SIZE_LIMIT = 4096;

    private int getMaxTextureSize() {
        // The OpenGL texture size is the maximum size that can be drawn in an ImageView
        int[] maxSize = new int[1];
        GLES10.glGetIntegerv(GLES10.GL_MAX_TEXTURE_SIZE, maxSize, 0);
        return maxSize[0];
    }

    private int getMaxImageSize() {
        int textureLimit = getMaxTextureSize();
        if (textureLimit == 0) {
            return SIZE_DEFAULT;
        } else {
            return Math.min(textureLimit, SIZE_LIMIT);
        }
    }


    public static void closeSilently(@Nullable Closeable c) {
        if (c == null) return;
        try {
            c.close();
        } catch (Throwable t) {
            // Do nothing
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_save:
                Bitmap bitmap = mClipImageLayout.clip();
                mClipImageLayout = null;
                Config.BUS_PICTURE_PATH = Config.getImagePath();
//			NativeUtil.compressBitmap(bitmap, Config.BUS_PICTURE_PATH, true);

                new AsyncImageTask(bitmap).execute();
//			Intent it = new Intent();
//			it.putExtra("images", Config.BUS_PICTURE_PATH);
//			setResult(RESULT_OK, it);
//			bm.recycle();
//			onBackPressed();
//			deleteFiles(picturePath);
                break;
            case android.R.id.home:
                onBackPressed();
                break;

            default:
                break;
        }

        return true;
    }


    private void deleteFiles(String picturePath) {
        File file = new File(picturePath);
        if (file.exists()) {
            file.getAbsoluteFile().delete();
        }
    }

    /**
     * 异步保存图片 bitmap
     */
    private final class AsyncImageTask extends AsyncTask<String, Integer, String> {

        private Bitmap bitmap;
        CustomProgressDialog progressDialog;

        public AsyncImageTask(Bitmap bitmap) {
            this.bitmap = bitmap;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new CustomProgressDialog(ClipImageActivity.this, "");
            progressDialog.showDialog();
        }

        // 后台运行的子线程子线程
        @Override
        protected String doInBackground(String... params) {
            try {
                PhotoUtilChange.compressBitmap(Config.BUS_PICTURE_PATH, bitmap);
//        c.close();
                if (bitmap != null) {
                    bitmap.recycle();
                }
                return "--";
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        // 这个放在在ui线程中执行
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressDialog.dismiss();
            // 完成图片的绑定
            if (result != null) {
                Intent it = new Intent();
                it.putExtra("images", Config.BUS_PICTURE_PATH);
                setResult(RESULT_OK, it);
                try {
                    bm.recycle();
                } catch (Exception e) {
//                    e.printStackTrace();
                    Toast.makeText(ClipImageActivity.this, "图片裁剪失败", Toast.LENGTH_SHORT).show();
                }
                onBackPressed();
            } else {
                Toast.makeText(ClipImageActivity.this, "图片裁剪失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


}
